// TypeScript 版本的个人页面
// 导入全局认证管理器和API
import { authManager } from '../../api/auth-manager';
import api from '../../api/index';
const i18n = require('../../i18n/index');

Page({
  data: {
    isLoggedIn: true, // 默认显示为已登录状态
    // 添加默认头像
    defaultAvatar: '../../image/NMlog.png',
    userInfo: {
      nickname: '智能水杯用户',
      uuid: '0000-0000-0000-0000-0000',
      id: null as number | null,
      dailyGoal: 2000,
      wxOpenid: null as string | null,
      reminderEnabled: 0
    },
    waterGoal: '2000',
    settings: {
      notification: false, // 默认关闭，需要通过API获取真实状态
      reminderEnabled: false,
      wxOpenidBound: false
    },
    appVersion: '1.0.6',
    // 来源信息
    fromOfficialAccount: false,
    launchScene: null,
    // 多语言文本
    l10n: {
      defaultNickname: '',
      loggedIn: '',
      loggedOut: '',
      waterGoal: '',
      drinkReminder: '',
      wxBound: '',
      wxUnbound: '',
      fromOfficialAccount: '',
      privacy: '',
      contactUs: '',
      checkUpdate: '',
      logout: '',
      languageTitle: ''
    },
    // 当前语言名
    currentLangName: ''
  },

  onLoad: function() {
    console.log('个人页面加载');
    this.initData();
  },

  onShow: function() {
    // TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({ selected: 2 });
    }
    
    // 刷新文案与导航标题
    this.updateTexts();
    
    // 检测来源信息
    const fromOfficialAccount = wx.getStorageSync('fromOfficialAccount') || false;
    const launchScene = wx.getStorageSync('launchScene') || null;
    this.setData({ fromOfficialAccount, launchScene });
    
    // 使用全局认证管理器检查登录状态
    const isLoggedIn = authManager.isAuthenticated();
    this.setData({ isLoggedIn });
    
    if (isLoggedIn) {
      // 获取用户信息（会在成功后自动更新提醒设置）
      this.loadUserInfo();
      // 获取饮水目标
      this.loadWaterGoal();
    } else {
      console.log('[onShow] 用户未登录，跳过加载用户数据');
    }
  },

  updateTexts: function() {
    const l10n = {
      defaultNickname: i18n.t('profile.defaultNickname'),
      loggedIn: i18n.t('profile.loggedIn'),
      loggedOut: i18n.t('profile.loggedOut'),
      waterGoal: i18n.t('profile.waterGoal'),
      drinkReminder: i18n.t('profile.drinkReminder'),
      wxBound: i18n.t('profile.wxBound'),
      wxUnbound: i18n.t('profile.wxUnbound'),
      fromOfficialAccount: i18n.t('profile.fromOfficialAccount'),
      privacy: i18n.t('profile.privacy'),
      contactUs: i18n.t('profile.contactUs'),
      checkUpdate: i18n.t('profile.checkUpdate'),
      logout: i18n.t('profile.logout'),
      languageTitle: i18n.t('language.title')
    };

    // 计算当前语言名
    const code = i18n.getLang();
    let currentLangName = '';
    if (code === 'zh-CN') currentLangName = i18n.t('language.zhCN');
    else if (code === 'zh-HK') currentLangName = i18n.t('language.zhHK');
    else currentLangName = i18n.t('language.enUS');

    this.setData({ l10n, currentLangName });
    try { wx.setNavigationBarTitle({ title: i18n.t('profile.title') }); } catch (e) {}
  },

  // 初始化数据
  initData: function() {
    // 初始化应用版本
    try {
      const accountInfo = wx.getAccountInfoSync();
      const appVersion = accountInfo.miniProgram.version || '1.0.0';
      this.setData({ appVersion });
    } catch (e) {
      console.error('获取版本信息失败:', e);
    }

    // 初始化默认头像
    const defaultAvatar = '../../image/NMlog.png';
    this.setData({ defaultAvatar });
  },

  // 加载用户信息
  loadUserInfo: function() {
    const self = this;
    
    console.log('[loadUserInfo] 开始获取用户信息');
    
    // 调用后端API获取用户信息
    api.getUserInfo().then((res: any) => {
      console.log('[loadUserInfo] 获取用户信息成功:', res);
      
      if (res && res.data && res.data.data) {
        const userData = res.data.data;
        
        // 更新用户信息，包括UUID
        const userInfo = {
          nickname: userData.nickname || userData.username || self.data.l10n.defaultNickname || '智能水杯用户',
          uuid: userData.uuid || String(userData.id || '0000-0000-0000-0000-0000'),
          id: userData.id,
          dailyGoal: userData.dailyGoal || 2000,
          wxOpenid: userData.wxOpenid || null,
          reminderEnabled: userData.reminderEnabled || 0
        };
        
        self.setData({ userInfo });
        
        // 缓存用户信息
        wx.setStorageSync('userInfo', userInfo);
        if (userData.id) {
          wx.setStorageSync('userId', userData.id);
        }
        
        console.log('[loadUserInfo] 用户信息已更新:', userInfo);
        
        // 用户信息获取成功后，立即更新提醒设置
        // 如果有wxOpenid，直接基于用户信息更新设置
        if (userInfo.wxOpenid && userInfo.wxOpenid.trim() !== '') {
          console.log('[loadUserInfo] 用户已有wxOpenid，直接更新设置');
          self.updateSettingsFromUserInfo();
        } else {
          // 没有wxOpenid，尝试从API获取更多信息
          console.log('[loadUserInfo] 用户无wxOpenid，从API获取提醒设置');
          self.loadReminderSettings();
        }
      }
    }).catch((error: any) => {
      console.error('[loadUserInfo] 获取用户信息失败:', error);
      
      // 使用本地缓存作为备用
      try {
        const storedUserInfo = wx.getStorageSync('userInfo');
        if (storedUserInfo) {
          self.setData({ userInfo: storedUserInfo });
          // 如果有缓存的用户信息，也更新提醒设置
          if (storedUserInfo.id) {
            if (storedUserInfo.wxOpenid && storedUserInfo.wxOpenid.trim() !== '') {
              console.log('[loadUserInfo] 缓存用户已有wxOpenid，直接更新设置');
              self.updateSettingsFromUserInfo();
            } else {
              console.log('[loadUserInfo] 缓存用户无wxOpenid，从API获取提醒设置');
              self.loadReminderSettings();
            }
          }
        }
      } catch (e) {
        console.error('读取本地用户信息失败:', e);
      }
    });
  },
  
  // 加载饮水目标
  loadWaterGoal: function() {
    const self = this;
    
    console.log('[loadWaterGoal] 开始获取饮水目标');
    
    // 调用后端API获取用户信息（包含饮水目标）
    api.getUserInfo().then((res: any) => {
      console.log('[loadWaterGoal] 获取用户信息和饮水目标成功:', res);
      
      if (res && res.data && res.data.data) {
        const userData = res.data.data;
        const dailyGoal = userData.dailyGoal || 2000;
        
        // 更新饮水目标
        self.setData({ 
          waterGoal: dailyGoal.toString(),
          userInfo: {
            ...self.data.userInfo,
            dailyGoal: dailyGoal
          }
        });
        
        // 缓存饮水目标
        wx.setStorageSync('waterGoal', dailyGoal.toString());
        
        console.log('[loadWaterGoal] 饮水目标已更新:', dailyGoal, 'ml');
      }
    }).catch((error: any) => {
      console.error('[loadWaterGoal] 获取饮水目标失败:', error);
      
      // 使用本地缓存作为备用
      try {
        const waterGoal = wx.getStorageSync('waterGoal') || '2000';
        self.setData({ waterGoal });
      } catch (e) {
        console.error('读取本地饮水目标失败:', e);
      }
    });
  },

  // 设置饮水目标
  setWaterGoal: function() {
    const currentGoal = this.data.waterGoal;
    const itemList = ['1000ml', '1500ml', '2000ml', '2500ml', '3000ml', i18n.t('water.customize')];
    
    // 如果当前目标在预设值中，添加标记
    const currentGoalNum = parseInt(currentGoal);
    const presetGoals = [1000, 1500, 2000, 2500, 3000];
    const currentIndex = presetGoals.indexOf(currentGoalNum);

    const langCode = (typeof i18n.getLang === 'function') ? i18n.getLang() : 'zh-CN';
    const currentTag = langCode === 'en-US' ? '(Current)' : (langCode === 'zh-HK' ? '(當前)' : '(当前)');

    if (currentIndex !== -1) {
      itemList[currentIndex] = `${presetGoals[currentIndex]}ml ${currentTag}`;
    }
    
    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        if (res.tapIndex === 5) {
          // 自定义
          wx.showModal({
            title: i18n.t('profile.setGoalTitle'),
            content: i18n.t('profile.setGoalCurrent', { current: currentGoal }),
            placeholderText: i18n.t('profile.setGoalPlaceholder'),
            editable: true,
            success: (res) => {
              if (res.confirm && res.content) {
                const goal = parseInt(res.content);
                if (goal > 0 && goal <= 5000) {
                  this.updateWaterGoal(goal);
                } else {
                  wx.showToast({
                    title: i18n.t('profile.setGoalInvalid'),
                    icon: 'none'
                  });
                }
              }
            }
          });
        } else {
          const goals = [1000, 1500, 2000, 2500, 3000];
          const waterGoal = goals[res.tapIndex];
          
          // 如果选择的是当前目标，不需要更新
          if (waterGoal === currentGoalNum) {
            wx.showToast({
              title: i18n.t('profile.setGoalUnchanged'),
              icon: 'none'
            });
            return;
          }
          
          this.updateWaterGoal(waterGoal);
        }
      }
    });
  },

  // 更新饮水目标
  updateWaterGoal: function(goal: number) {
    const self = this;
    
    console.log('[updateWaterGoal] 开始更新饮水目标:', goal);
    
    // 显示加载提示
    wx.showLoading({
      title: i18n.t('profile.settingGoalLoading'),
      mask: true
    });
    
    // 调用后端API更新饮水目标
    api.updateDailyTarget(goal).then((res: any) => {
      console.log('[updateWaterGoal] 更新饮水目标成功:', res);
      
      // 更新本地数据
      self.setData({ 
        waterGoal: goal.toString(),
        userInfo: {
          ...self.data.userInfo,
          dailyGoal: goal
        }
      });
      
      // 缓存饮水目标
      wx.setStorageSync('waterGoal', goal.toString());
      
      wx.hideLoading();
      wx.showToast({
        title: i18n.t('profile.goalSet'),
        icon: 'success'
      });
      
      // 重新加载饮水目标以确保数据同步
      setTimeout(() => {
        self.loadWaterGoal();
      }, 1000);
      
    }).catch((error: any) => {
      console.error('[updateWaterGoal] 更新饮水目标失败:', error);
      wx.hideLoading();
      
      // 先更新本地数据作为备用
      self.setData({ 
        waterGoal: goal.toString(),
        userInfo: {
          ...self.data.userInfo,
          dailyGoal: goal
        }
      });
      wx.setStorageSync('waterGoal', goal.toString());
      
      wx.showModal({
        title: i18n.t('profile.syncFailedTitle'),
        content: i18n.t('profile.syncFailedContent'),
        showCancel: true,
        cancelText: i18n.t('profile.retryLater'),
        confirmText: i18n.t('profile.retrySync'),
        success: (res) => {
          if (res.confirm) {
            // 重新尝试同步
            self.updateWaterGoal(goal);
          }
        }
      });
    });
  },

  // 加载提醒设置
  loadReminderSettings: function() {
    const userInfo = this.data.userInfo;
    if (!userInfo.id) {
      console.log('[loadReminderSettings] 用户ID不存在，跳过加载提醒设置');
      return;
    }

    console.log('[loadReminderSettings] 开始获取提醒设置');
    console.log('[loadReminderSettings] 当前用户信息:', userInfo);
    
    // 首先检查用户信息中是否已有wxOpenid
    const hasWxOpenid = userInfo.wxOpenid && userInfo.wxOpenid.trim() !== '';
    console.log('[loadReminderSettings] 检查用户wxOpenid:', { 
      hasWxOpenid, 
      wxOpenid: userInfo.wxOpenid,
      reminderEnabled: userInfo.reminderEnabled
    });
    
    // 如果用户信息中没有wxOpenid，尝试从API获取
    if (!hasWxOpenid) {
      console.log('[loadReminderSettings] 用户信息中无wxOpenid，尝试从API获取');
      api.getReminderSettings(userInfo.id).then((res: any) => {
        console.log('[loadReminderSettings] 获取提醒设置成功:', res);
        console.log('[loadReminderSettings] API返回完整数据:', JSON.stringify(res, null, 2));
        
        if (res && res.data && res.data.data) {
          const reminderData = res.data.data;
          console.log('[loadReminderSettings] 解析后的reminderData:', reminderData);
          
          // 🔧 修复：分别记录各个状态
          const wxOpenidBound = !!reminderData.wxOpenidBound;
          const reminderEnabled = !!reminderData.reminderEnabled;
          const isNotificationEnabled = wxOpenidBound && reminderEnabled;
          
          console.log('[loadReminderSettings] 状态计算:', {
            wxOpenidBound,
            reminderEnabled, 
            isNotificationEnabled,
            originalWxOpenidBound: reminderData.wxOpenidBound,
            originalReminderEnabled: reminderData.reminderEnabled
          });
          
          const settings = {
            ...this.data.settings,
            notification: isNotificationEnabled, // 只有绑定公众号且开启提醒时才为true
            reminderEnabled: reminderEnabled,
            wxOpenidBound: wxOpenidBound
          };
          
          this.setData({ settings });
          console.log('[loadReminderSettings] 提醒设置已更新:', {
            ...settings,
            logic: `wxOpenidBound(${wxOpenidBound}) && reminderEnabled(${reminderEnabled}) = notification(${isNotificationEnabled})`
          });
        } else {
          console.log('[loadReminderSettings] API返回数据格式异常:', res);
        }
      }).catch((error: any) => {
        console.error('[loadReminderSettings] 获取提醒设置失败:', error);
        this.updateSettingsFromUserInfo();
      });
    } else {
      // 用户信息中已有wxOpenid，直接更新设置
      console.log('[loadReminderSettings] 用户信息中已有wxOpenid，直接更新设置');
      this.updateSettingsFromUserInfo();
    }
  },

    // 从用户信息更新设置
  updateSettingsFromUserInfo: function() {
    const userInfo = this.data.userInfo;
    const hasWxOpenid = userInfo.wxOpenid && userInfo.wxOpenid.trim() !== '';
    
    console.log('[updateSettingsFromUserInfo] 从用户信息更新设置:', {
      hasWxOpenid,
      wxOpenid: userInfo.wxOpenid,
      reminderEnabled: userInfo.reminderEnabled,
      userInfoFull: userInfo
    });
    
    // 🔧 修复：更宽松的判断逻辑
    const wxOpenidBound = !!hasWxOpenid;
    
    // 🎯 关键修复：如果用户有wxOpenid，默认认为提醒已开启（除非明确为0）
    // 因为有wxOpenid意味着用户曾经开启过提醒功能
    let reminderEnabled = false;
    if (hasWxOpenid) {
      // 有wxOpenid的情况下，只要不是明确的0，都认为是开启状态
      reminderEnabled = userInfo.reminderEnabled !== 0;
      console.log('[updateSettingsFromUserInfo] 🎯 检测到有wxOpenid，reminderEnabled状态:', {
        原始值: userInfo.reminderEnabled,
        处理后: reminderEnabled,
        逻辑: '有wxOpenid且不为0则开启'
      });
    } else {
      // 没有wxOpenid的情况下，严格按照reminderEnabled字段
      reminderEnabled = userInfo.reminderEnabled === 1;
    }
    
    // 通知开关：有wxOpenid且提醒开启
    const isNotificationEnabled = wxOpenidBound && reminderEnabled;
    
    console.log('[updateSettingsFromUserInfo] 状态计算详细:', {
      hasWxOpenid,
      wxOpenidBound,
      reminderEnabled,
      reminderEnabledValue: userInfo.reminderEnabled,
      isNotificationEnabled,
      logic: `wxOpenidBound(${wxOpenidBound}) && reminderEnabled(${reminderEnabled}) = notification(${isNotificationEnabled})`
    });
    
    const settings = {
      ...this.data.settings,
      notification: isNotificationEnabled,
      reminderEnabled: reminderEnabled,
      wxOpenidBound: wxOpenidBound
    };
    
    this.setData({ settings });
    console.log('[updateSettingsFromUserInfo] 设置已更新:', settings);
    
    // 缓存设置
    wx.setStorageSync('settings', settings);
  },

  // 切换消息通知 - 实现两个功能：绑定公众号openid + 开启/关闭提醒
  toggleNotification: function() {
    const { userInfo, settings, fromOfficialAccount, launchScene } = this.data;
    
    // 检查是否已登录
    if (!userInfo.id) {
      wx.showModal({
        title: i18n.t('profile.needLoginTitle'),
        content: i18n.t('profile.needLoginContent'),
        showCancel: false
      });
      return;
    }

    const currentEnabled = settings.notification;
    const targetEnabled = !currentEnabled;

    console.log(`[toggleNotification] 准备${targetEnabled ? '开启' : '关闭'}消息通知`);
    console.log('[toggleNotification] 来源信息:', { fromOfficialAccount, launchScene });

    // 如果要开启提醒，需要先处理微信绑定
    if (targetEnabled) {
      // 🔧 修复：如果用户已经有wx_openid，直接开启提醒
      if (userInfo.wxOpenid && userInfo.wxOpenid.trim() !== '') {
        console.log('[toggleNotification] 🎯 用户已有wx_openid，直接开启提醒');
        this.toggleReminderOnly(userInfo.id, targetEnabled);
        return;
      }
      
      // 检查是否来自公众号
      if (fromOfficialAccount) {
        console.log('[toggleNotification] 🎯 检测到来自公众号，开始绑定流程');
        
        wx.showModal({
          title: i18n.t('profile.enableReminderTitle'),
          content: i18n.t('profile.enableReminderContentOA'),
          confirmText: i18n.t('profile.enableNow'),
          cancelText: i18n.t('common.cancel'),
          success: (res) => {
            if (res.confirm && userInfo.id) {
              this.bindWechatAndEnableReminder(userInfo.id, launchScene || undefined);
            }
          }
        });
      } else {
        // 不是来自公众号，提示用户
        wx.showModal({
          title: i18n.t('profile.enableReminderTitle'),
          content: i18n.t('profile.enableLocalReminderContent'),
          confirmText: i18n.t('profile.enableLocal'),
          cancelText: i18n.t('common.cancel'),
          success: (res) => {
            if (res.confirm && userInfo.id) {
              this.toggleReminderOnly(userInfo.id, targetEnabled);
            }
          }
        });
      }
         } else {
       // 关闭提醒，直接调用API
       if (userInfo.id) {
         this.toggleReminderOnly(userInfo.id, targetEnabled);
       }
     }
  },

  // 绑定微信公众号并开启提醒
  bindWechatAndEnableReminder: function(userId: number, scene?: number) {
    console.log('[bindWechatAndEnableReminder] 开始绑定微信并开启提醒');
    
    // 获取来源公众号AppID
    const referrerAppId = wx.getStorageSync('referrerAppId');
    
    api.bindWechatOpenid({
      userId: userId,
      scene: scene,
      referrerAppId: referrerAppId
    }).then((res: any) => {
      console.log('[bindWechatAndEnableReminder] 绑定微信成功:', res);
      
      // 绑定成功后，开启提醒
      return api.toggleReminder(userId, true);
    }).then((res: any) => {
      console.log('[bindWechatAndEnableReminder] 开启提醒成功:', res);
      
      // 更新本地状态
      const settings = {
        ...this.data.settings,
        notification: true,
        reminderEnabled: true,
        wxOpenidBound: true
      };
      this.setData({ settings });
      wx.setStorageSync('settings', settings);
      
      wx.showModal({
        title: i18n.t('profile.bindAndEnableSuccessTitle'),
        content: i18n.t('profile.bindAndEnableSuccessContent'),
        showCancel: false,
        confirmText: i18n.t('common.ok')
      });
      
    }).catch((error: any) => {
      console.error('[bindWechatAndEnableReminder] 操作失败:', error);
      
      let errorMsg = i18n.t('profile.bindFailedContentDefault');
      if (error.message && error.message.includes('公众号')) {
        errorMsg = i18n.t('profile.bindFailedContentOA');
      }
      
      wx.showModal({
        title: i18n.t('profile.bindFailedTitle'),
        content: errorMsg,
        showCancel: false
      });
    });
  },

  // 仅切换提醒状态（不处理微信绑定）
  toggleReminderOnly: function(userId: number, enabled: boolean) {
    console.log(`[toggleReminderOnly] ${enabled ? '开启' : '关闭'}提醒功能`);
    
    api.toggleReminder(userId, enabled).then((res: any) => {
      console.log('[toggleReminderOnly] 切换提醒状态成功:', res);
      
      // 更新本地状态
      const settings = {
        ...this.data.settings,
        notification: enabled,
        reminderEnabled: enabled
      };
      this.setData({ settings });
      wx.setStorageSync('settings', settings);
      
      wx.showToast({
        title: enabled ? i18n.t('profile.reminderOn') : i18n.t('profile.reminderOff'),
        icon: 'success'
      });
      
      // 如果是开启状态但没有绑定微信，给出提示
      if (enabled && !settings.wxOpenidBound) {
        setTimeout(() => {
          wx.showToast({
            title: i18n.t('profile.suggestBind'),
            icon: 'none',
            duration: 3000
          });
        }, 1500);
      }
      
    }).catch((error: any) => {
      console.error('[toggleReminderOnly] 切换提醒状态失败:', error);
      
      // 先更新本地状态作为备用
      const settings = {
        ...this.data.settings,
        notification: enabled,
        reminderEnabled: enabled
      };
      this.setData({ settings });
      wx.setStorageSync('settings', settings);
      
      wx.showModal({
        title: i18n.t('profile.syncFailedTitle'),
        content: i18n.t('profile.syncFailedContent'),
        showCancel: true,
        cancelText: i18n.t('profile.retryLater'),
        confirmText: i18n.t('profile.retrySync'),
        success: (res) => {
          if (res.confirm) {
            this.toggleReminderOnly(userId, enabled);
          }
        }
      });
    });
  },

  // 跳转到隐私政策
  goToPrivacy: function() {
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    });
  },

  // 联系我们
  contactUs: function() {
    wx.showModal({
      title: i18n.t('profile.contactModalTitle'),
      content: i18n.t('profile.contactModalContent'),
      showCancel: false,
      confirmText: i18n.t('common.ok')
    });
  },

  // 检查更新
  checkUpdate: function() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      
      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(() => {
            wx.showModal({
              title: i18n.t('profile.updateTitle'),
              content: i18n.t('profile.updateContent'),
              success: (res) => {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              }
            });
          });
          
          updateManager.onUpdateFailed(() => {
            wx.showModal({
              title: i18n.t('profile.updateFailedTitle'),
              content: i18n.t('profile.updateFailedContent'),
              showCancel: false
            });
          });
        } else {
          wx.showToast({
            title: i18n.t('profile.alreadyLatest'),
            icon: 'none'
          });
        }
      });
    } else {
      wx.showModal({
        title: i18n.t('profile.lowWechatTitle'),
        content: i18n.t('profile.lowWechatContent'),
        showCancel: false
      });
    }
  },

  // 跳转到微信模板消息测试页面
  goToWechatTest: function() {
    console.log('点击了微信模板消息测试按钮');
    wx.navigateTo({
      url: '/pages/wechat-test/wechat-test',
      success: () => {
        console.log('成功跳转到微信测试页面');
      },
      fail: (error) => {
        console.error('跳转失败:', error);
        wx.showToast({
          title: i18n.t('profile.pageJumpFailed'),
          icon: 'error'
        });
      }
    });
  },

  // 退出登录
  logout: function() {
    wx.showModal({
      title: i18n.t('profile.logoutTitle'),
      content: i18n.t('profile.logoutContent'),
      cancelText: i18n.t('common.cancel'),
      confirmText: i18n.t('common.ok'),
      success: async (res) => {
        if (res.confirm) {
          try {
            // 使用全局认证管理器登出
            try {
              await authManager.logout();
              
              // 重置界面状态
              this.setData({
                isLoggedIn: false,
                userInfo: {
                  nickname: this.data.l10n.defaultNickname || '智能水杯用户',
                  uuid: '0000-0000-0000-0000-0000',
                  id: null,
                  dailyGoal: 2000,
                  wxOpenid: null,
                  reminderEnabled: 0
                },
                waterGoal: '2000'
              });
            } catch (error) {
              console.error('登出失败:', error);
            }
            
            wx.showToast({
              title: i18n.t('profile.loggedOutToast'),
              icon: 'success'
            });
            
            setTimeout(() => {
              wx.switchTab({ url: '/pages/index/index' });
            }, 1000);
            
          } catch (error) {
            console.error('退出登录失败:', error);
            wx.showToast({
              title: i18n.t('profile.logoutFailed'),
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 跳转语言设置
  goToLanguage: function() {
    wx.navigateTo({ url: '/pages/language/language' });
  }
})



